package woaini.fenger.core.bot.id;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.annotation.JSONField;
import com.alibaba.fastjson2.reader.ObjectReader;
import com.alibaba.fastjson2.writer.ObjectWriter;
import lombok.Getter;
import lombok.Setter;

import java.lang.reflect.Type;
import java.util.Objects;

/**
 * ID 封装可以是任何类型的id 一般就2个 数字和字符串
 *
 * @see ID
 * @author yefeng {@code @Date} 2023-05-16 16:50:39
 */
@Getter
@Setter
public class ID {

  /**
   * @see String 值
   */
  private String value;

  public ID(String value) {
    this.value = value;
  }

  public static ID of(String value) {
    return new ID(value);
  }

  public static ID of(Long value) {
    return new ID(value.toString());
  }
  public static ID of(Integer value) {
    return new ID(value.toString());
  }
  private String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }

  public void setValue(Long value) {
    this.value = value.toString();
  }

  @JSONField(deserialize = false,serialize = false)
  public Long getLongValue() {
    return Long.valueOf(value);
  }
  @Override
  public String toString() {
    return value;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (o == null || getClass() != o.getClass()) {
        return false;
    }
    ID id = (ID) o;
    return Objects.equals(value, id.value);
  }
  @Override
  public int hashCode() {
    return Objects.hash(value);
  }

  public static class Deserializer implements ObjectReader<ID> {

    @Override
    public ID readObject(
            JSONReader jsonReader, Type fieldType, Object fieldName, long features) {
      if (jsonReader.nextIfNull()) {
        return null;
      }
      Object read = jsonReader.read(fieldType);
      return ID.of(read.toString());
    }
  }

  public static class Serializer<ID> implements ObjectWriter<ID> {

    @Override
    public void write(JSONWriter jsonWriter, Object o, Object o1, Type type, long l) {
      woaini.fenger.core.bot.id.ID o2 = (woaini.fenger.core.bot.id.ID) o;
      jsonWriter.writeInt64(o2.getLongValue());
    }
  }
}
